package com.carrot.gateway.filter.handler.auth;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.carrot.common.core.domain.R;
import com.carrot.common.enums.BaseMsg;
import com.carrot.gateway.util.AuthUtil;
import com.carrot.gateway.util.ResultUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * v1及按照规则未解析到api版本
 */
@NoArgsConstructor
public abstract class AbstractAuthHandler implements IAuthHandler {

    RedisTemplate<String, Object> redisTemplate;
    ObjectMapper objectMapper;

    /**
     * 处理 Token
     * @param headers 头部
     * @param key Key
     * @return String
     */
    String handleToken(HttpHeaders headers, String key){
       return AuthUtil.handleToken(headers,key);
    }

    /**
     * 异常返回
     * @param response response
     * @param baseMsg 异常枚举
     * @return Mono
     */
    Mono<Void> errorResult(ServerHttpResponse response, BaseMsg baseMsg) {
        R<?> customResultWrapper = R.fail(baseMsg);
        return ResultUtil.result(response, objectMapper, customResultWrapper);
    }

    /**
     * 将用户信息存为jwt格式 TODO 加缓存
     * @param jsonUserInfo
     * @return
     */
    String jwtUserInfo(JSONObject jsonUserInfo){
        Map<String, Object> map = new HashMap<String, Object>(6) {
            private static final long serialVersionUID = 1L;
            {
                put("userTypeEnum", jsonUserInfo.get("userTypeEnum")==null?
                        jsonUserInfo.get("userType"):jsonUserInfo.get("userTypeEnum"));
                put("mobile", jsonUserInfo.get("mobile"));
                put("userIdentityType", jsonUserInfo.get("userIdentityType")==null?
                        jsonUserInfo.get("identityType"):jsonUserInfo.get("userIdentityType"));
                put("uid", jsonUserInfo.get("uid"));
                put("tenantId", jsonUserInfo.get("tenantId"));
                put("nickname", jsonUserInfo.get("nickname"));
            }
        };

        return "Bearer "+ JWTUtil.createToken(map,"1234".getBytes());
    }

    /**
     * 从redis中获取用户信息
     * @param accessTokenKey
     * @return
     */
    JSONObject getUserInfoForRedis(String accessTokenKey){
        Object userInfo = redisTemplate.opsForValue().get(accessTokenKey);
        return JSONUtil.parseObj(userInfo);
    }
}
